package net.chrisrichardson.ec2deployer.cluster

import groovy.mock.interceptor.MockFor
import net.chrisrichardson.ec2deployer.core.AWSProperties
import net.chrisrichardson.ec2deployer.core.EC2
import net.chrisrichardson.ec2deployer.core.EC2Server
import net.chrisrichardson.ec2deployer.util.FileBasedTemplate
import net.chrisrichardson.ec2deployer.applications.CatalinaOptionsBuilder

class TerracottaTierTest extends GroovyTestCase {

    def mockEc2
    def awsProperties
    def clusterSpec
    def mockEc2Server

    public void setUp() {
        mockEc2 = new MockFor(EC2.class)
        mockEc2Server = new MockFor(EC2Server)
        def props = new Properties()
        awsProperties = new AWSProperties(props)

        clusterSpec = new ClusterSpec().tomcats(1).slaves(1).webApp('target/ptrack', "ptrack").catalinaOptsBuilder({builder, databasePrivateDnsName ->}).schema("ptrack", ["ptrack": "ptrack"]).terracottaHosts(1)

    }

    public void testAssignHosts() {

        def ec2 = new EC2(awsProperties)

        def terracottaInstance = new EC2Server()
        def hosts = new ClusterHosts(terracottaHosts: [terracottaInstance])
        TerracottaTier terracottaServerTier = new TerracottaTier(ec2, clusterSpec)
        terracottaServerTier.assignHosts(hosts)

        assertEquals 1, terracottaServerTier.terracottaServers.size()
    }

    public void testStart() {

        def ec2 = new EC2(awsProperties)
        def mockFileBasedTemplate = new MockFor(FileBasedTemplate)

        mockFileBasedTemplate.demand.process {templateName, args ->
            "foo"
        }

        mockEc2Server.demand.ssh{ command, input ->
            assertEquals "cat > /root/tc-config.xml", command
            assertEquals "foo", input
        }
        
        mockEc2Server.demand.ssh{ command ->
            assertTrue("Unxpected $command", command.startsWith("(export "))
        }

        mockEc2Server.use {
            def terracottaInstance = new EC2Server()
            def hosts = new ClusterHosts(terracottaHosts: [terracottaInstance])
            TerracottaTier terracottaServerTier = new TerracottaTier(ec2, clusterSpec)
            terracottaServerTier.assignHosts(hosts)

            mockFileBasedTemplate.use {
                terracottaServerTier.start()
            }
        }

    }

    public void testAddToCatalinaOpts() {
        def ec2 = new EC2(awsProperties)
        CatalinaOptionsBuilder builder = new CatalinaOptionsBuilder()
        TerracottaTier terracottaTier = new TerracottaTier(ec2, clusterSpec)
        terracottaTier.addToCatalinaOpts(builder)
        assertEquals " -Xbootclasspath/p:/var/lib/tomcat5/dso-boot.jar -Dtc.install-root=/var/lib/terracotta-2.5.4 -Dtc.config=/var/lib/tomcat5/tc-config.xml", builder.options
    }

}